package com.qiantu.phone.ui.fragment.device;

import android.app.Activity;
import android.content.Intent;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.SeekBar;
import android.widget.TextView;

import androidx.lifecycle.LifecycleOwner;

import com.bumptech.glide.load.resource.bitmap.CenterCrop;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;
import com.hjq.http.listener.HttpCallback;
import com.hjq.toast.ToastUtils;
import com.qiantu.api.db.LLDeviceDBManager;
import com.qiantu.api.entity.DeviceState;
import com.qiantu.api.http.LLHttpManager;
import com.qiantu.api.http.model.HttpData;
import com.qiantu.phone.R;
import com.qiantu.phone.app.AppActivity;
import com.qiantu.phone.glide.GlideApp;
import com.qiantu.phone.ui.activity.PlayMusicListActivity;
import com.qiantu.phone.ui.activity.PlayMusicSearchActivity;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.TimeZone;
import java.util.Timer;
import java.util.TimerTask;

import okhttp3.Call;

/**
 *    desc   : 音乐设备
 */
public final class MusicFragment extends BaseDeviceFragment implements View.OnClickListener {
    public static int requCode = 126;
    private TextView tv_musicName;
    private TextView tv_singerName;
    private TextView tv_aggregate_scheduling;
    private TextView tv_Current_progress;
    private ImageView icon_music_list;
    private ImageView icon_music_tacitlyapprove;
    private ImageView icon_music_sound;
    private ImageView icon_music_randomcycle;
    private ImageView iv_music_like;
    private ImageView iv_stop_playing;
    private SeekBar volume_length;
    private SeekBar progress_length;
    private LinearLayout ll_seekbar_volume;
    private boolean ifVolume = true;
    private DeviceState.StatusDTO status;
    private SimpleDateFormat simpleDateFormat = new SimpleDateFormat("mm:ss", Locale.CHINA);
    private String song_pic_url;
    private String song_name;
    private String song_auth;
    private Timer timer;
    private int current_progress = 0; //当前音乐进度
    private boolean isSeekBarChanging = false;  //互斥变量，防止进度条与定时器冲突。
    private int playmode = 0;

    public static MusicFragment newInstance() {
        MusicFragment fragment = new MusicFragment();
        return fragment;
    }


    @Override
    protected int getLayoutId() {
        return R.layout.fragment_music_device;
    }

    @Override
    protected void initView() {
        super.initView();
        tv_musicName = findViewById(R.id.tv_musicName);
        tv_singerName = findViewById(R.id.tv_singerName);
        tv_aggregate_scheduling = findViewById(R.id.tv_aggregate_scheduling);
        tv_Current_progress = findViewById(R.id.tv_Current_progress);
        icon_music_list = findViewById(R.id.icon_music_list);
        icon_music_randomcycle = findViewById(R.id.icon_music_randomcycle);
        icon_music_tacitlyapprove = findViewById(R.id.icon_music_tacitlyapprove);
        ll_seekbar_volume = findViewById(R.id.ll_seekbar_volume);
        icon_music_sound = findViewById(R.id.icon_music_sound);
        volume_length = findViewById(R.id.volume_length);
        progress_length = findViewById(R.id.progress_length);
        iv_music_like = findViewById(R.id.iv_music_like);
        iv_stop_playing = findViewById(R.id.iv_stop_playing);
        setOnClickListener(R.id.tv_musicName,
                R.id.icon_music_list,
                R.id.iv_next_music,
                R.id.iv_last_music,
                R.id.icon_music_sound,
                R.id.iv_music_like,
                R.id.iv_stop_playing,
                R.id.icon_music_randomcycle);
        timer=new Timer();
        isSeekBarChanging = iv_stop_playing.isSelected();
        play();
        updateView();
    }



    @Override
    public void onClick(View view) {
        super.onClick(view);
        switch (view.getId()){
            case R.id.tv_musicName:
                break;
            case R.id.icon_music_list:
                String key = mDevice.getVersion().substring(0,1);
                if(key.equals("1")){
                    Intent intent = new Intent(getContext(), PlayMusicListActivity.class);
                    intent.putExtra("serialNo",mDevice.getDeviceSerialNo());
                    intent.putExtra("controllerserialNo",mDevice.getControllerSerialNo());
                    intent.putExtra("songname",song_name);
                    startActivity(intent);
                }else{
                    Intent intent = new Intent(getContext(), PlayMusicSearchActivity.class);
                    intent.putExtra("serialNo",mDevice.getDeviceSerialNo());
                    startActivity(intent);
                }
                break;
            case R.id.iv_next_music:
                    nextOperation(0);
                break;
            case R.id.iv_last_music:
                    nextOperation(1);
                break;
            case R.id.icon_music_sound:
                if (icon_music_sound.isSelected()){
                    icon_music_sound.setSelected(false);
                    ifVolume = true;
                }
                if (ifVolume){
                    ll_seekbar_volume.setVisibility(View.VISIBLE);
                }else {
                    ll_seekbar_volume.setVisibility(View.GONE);
                }
                ifVolume = !ifVolume;
                break;
            case R.id.iv_music_like:
                iv_music_like.setSelected(!iv_music_like.isSelected());
                if (iv_music_like.isSelected()){
                    ToastUtils.show(R.string.music_like);
                    getSetFavouritemusic(iv_music_like.isSelected());
                }else {
                    ToastUtils.show(R.string.music_dislike);
                    getSetFavouritemusic(iv_music_like.isSelected());
                }
                break;
            case R.id.iv_stop_playing:
                playOperation(iv_stop_playing.isSelected() ? 1 : 0);
                if (iv_stop_playing.isSelected()){
                    isSeekBarChanging = true;
                }else{
//                    暂停之后结束定时器
                    isSeekBarChanging = false;
                }
                iv_stop_playing.setSelected(!iv_stop_playing.isSelected());
                break;
            case R.id.icon_music_randomcycle:
                if (playmode==2){
                    icon_music_randomcycle.setImageResource(R.mipmap.icon_music_listloop);
                    playmode = 3;
                }else if(playmode==3){
                    icon_music_randomcycle.setImageResource(R.mipmap.icon_music_randomcycle);
                    playmode = 5;
                }else if(playmode==5){
                    icon_music_randomcycle.setImageResource(R.mipmap.icon_music_loopplayback);
                    playmode = 6;
                }else if(playmode==6){
                    icon_music_randomcycle.setImageResource(R.mipmap.icon_music_singlecycle);
                    playmode = 2;
                }
                playModeOperation(playmode);
                break;
        }
    }

    private void play() {
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                if (getActivity()==null){
                    return;
                }
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (isSeekBarChanging){
                            current_progress++;
                            if (current_progress > status.getLength()){
                                isSeekBarChanging = false;
                            }else {
                                progress_length.setProgress(current_progress);
                                String progress_format = simpleDateFormat.format(new Date(current_progress * 1000));
                                tv_Current_progress.setText(progress_format);
                            }
                        }
                    }
                });
            }
        },660,1000);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        timer.cancel();
    }

    //收藏歌曲
    private void getSetFavouritemusic(Boolean isFavourite) {
        String[] musicIDS=new String[]{status.getSongid()};
        LLHttpManager.getSetFavouriteMusic(this,mDevice.getDeviceSerialNo(),musicIDS,isFavourite,new HttpCallback<HttpData<Void>>(this){
            @Override
            public void onStart(Call call) {
                super.onStart(call);
            }

            @Override
            public void onSucceed(HttpData<Void> result) {
                super.onSucceed(result);
            }

            @Override
            public void onFail(Exception e) {
                super.onFail(e);
            }

            @Override
            public void onEnd(Call call) {
                super.onEnd(call);
            }
        });
    }
    //音量控制
    private void seekBar_volume(){
        final int[] progress_volume = new int[1];
        volume_length.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                progress_volume[0] = progress;
                if (progress==0){
                    icon_music_sound.setSelected(true);
                    ll_seekbar_volume.setVisibility(View.GONE);
                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                volumeOperation(progress_volume[0]);
                ToastUtils.show(""+progress_volume[0]);
            }
        });
    }
    //音乐控制
    private int music_progress;
    private void seekBar_progress(){
        progress_length.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                music_progress = progress;
                String progress_format = simpleDateFormat.format(new Date(progress * 1000));
                tv_Current_progress.setText(progress_format);
            }
            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                isSeekBarChanging = false;
            }
            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                current_progress = music_progress;
                progressOperation(music_progress);
                if (!iv_stop_playing.isSelected()){
                    isSeekBarChanging = true;
                }

            }
        });
    }

    private void volumeOperation(int progress) {
        Map<String,Object> map=new HashMap<>();
        Map<String,Object> status=new HashMap<>();
        map.put("volume",progress);
        status.put(STATUS,map);
        LLHttpManager.operationDevice((LifecycleOwner) getContext(),mDevice.getDeviceSerialNo(),status,new HttpCallback<HttpData<Void>>(null){
            @Override
            public void onStart(Call call) {
                if(getContext() != null && getContext() instanceof AppActivity){
                    ((AppActivity) getContext()).showDialog("执行中...");
                }
            }

            @Override
            public void onSucceed(HttpData<Void> result) {
                super.onSucceed(result);
                mDevice.getStateData().getStatus().setVolume(progress);
                volume_length.setProgress(mDevice.getStateData().getStatus().getVolume());
                LLDeviceDBManager.getInstance(getContext()).put(mDevice);
                refreshDeviceStateByLocal();
            }

            @Override
            public void onFail(Exception e) {
                ToastUtils.show(R.string.exec_failure);
            }

            @Override
            public void onEnd(Call call) {
                if(getContext() != null && getContext() instanceof AppActivity) {
                    ((AppActivity) getContext()).hideDialog();
                }
            }
        });
    }

    private void nextOperation(int i) {
        Map<String,Object> map=new HashMap<>();
        Map<String,Object> status=new HashMap<>();
        map.put("next",i);
        status.put(STATUS,map);
        LLHttpManager.operationDevice((LifecycleOwner) getContext(),mDevice.getDeviceSerialNo(),status,new HttpCallback<HttpData<Void>>(null){
            @Override
            public void onStart(Call call) {
                if(getContext() != null && getContext() instanceof AppActivity){
                    ((AppActivity) getContext()).showDialog("执行中...");
                }
            }

            @Override
            public void onSucceed(HttpData<Void> result) {
                super.onSucceed(result);
                iv_music_like.setSelected(false);
                LLDeviceDBManager.getInstance(getContext()).put(mDevice);
                refreshDeviceStateByLocal();
            }

            @Override
            public void onFail(Exception e) {
                ToastUtils.show(R.string.exec_failure);
            }

            @Override
            public void onEnd(Call call) {
                if(getContext() != null && getContext() instanceof AppActivity) {
                    ((AppActivity) getContext()).hideDialog();
                }
            }
        });
    }

    private void playOperation(int playstate) {
        Map<String,Object> map=new HashMap<>();
        Map<String,Object> status=new HashMap<>();
        map.put("playstate",playstate);
        status.put(STATUS,map);
        LLHttpManager.operationDevice((LifecycleOwner) getContext(),mDevice.getDeviceSerialNo(),status,new HttpCallback<HttpData<Void>>(null){
            @Override
            public void onStart(Call call) {
                if(getContext() != null && getContext() instanceof AppActivity){
                    ((AppActivity) getContext()).showDialog("执行中...");
                }
            }

            @Override
            public void onSucceed(HttpData<Void> result) {
                super.onSucceed(result);
                mDevice.getStateData().getStatus().setPlaystate(playstate);
                iv_stop_playing.setSelected(mDevice.getStateData().getStatus().getPlaystate() == 0);
                LLDeviceDBManager.getInstance(getContext()).put(mDevice);
                refreshDeviceStateByLocal();
            }

            @Override
            public void onFail(Exception e) {
                ToastUtils.show(R.string.exec_failure);
            }

            @Override
            public void onEnd(Call call) {
                if(getContext() != null && getContext() instanceof AppActivity) {
                    ((AppActivity) getContext()).hideDialog();
                }
            }
        });
    }

    private void playModeOperation(int mode) {
        Map<String,Object> map=new HashMap<>();
        Map<String,Object> status=new HashMap<>();
        map.put("playmode",mode);
        status.put(STATUS,map);
        LLHttpManager.operationDevice((LifecycleOwner) getContext(),mDevice.getDeviceSerialNo(),status,new HttpCallback<HttpData<Void>>(null){
            @Override
            public void onStart(Call call) {
                if(getContext() != null && getContext() instanceof AppActivity){
                    ((AppActivity) getContext()).showDialog("执行中...");
                }
            }

            @Override
            public void onSucceed(HttpData<Void> result) {
                super.onSucceed(result);
                LLDeviceDBManager.getInstance(getContext()).put(mDevice);
                refreshDeviceStateByLocal();
            }

            @Override
            public void onFail(Exception e) {
                ToastUtils.show(R.string.exec_failure);
            }

            @Override
            public void onEnd(Call call) {
                if(getContext() != null && getContext() instanceof AppActivity) {
                    ((AppActivity) getContext()).hideDialog();
                }
            }
        });
    }

    private void progressOperation(int progress) {
        Map<String,Object> map=new HashMap<>();
        Map<String,Object> statusMap=new HashMap<>();
        map.put("progress",progress);
        statusMap.put(STATUS,map);
        LLHttpManager.operationDevice((LifecycleOwner) getContext(),mDevice.getDeviceSerialNo(),statusMap,new HttpCallback<HttpData<Void>>(null){
            @Override
            public void onStart(Call call) {
                if(getContext() != null && getContext() instanceof AppActivity){
                    ((AppActivity) getContext()).showDialog("执行中...");
                }
            }

            @Override
            public void onSucceed(HttpData<Void> result) {
                super.onSucceed(result);
                mDevice.getStateData().getStatus().setProgress(progress);
                progress_length.setProgress(mDevice.getStateData().getStatus().getProgress());
                LLDeviceDBManager.getInstance(getContext()).put(mDevice);
                refreshDeviceStateByLocal();
            }

            @Override
            public void onFail(Exception e) {
                ToastUtils.show(R.string.exec_failure);
            }

            @Override
            public void onEnd(Call call) {
                if(getContext() != null && getContext() instanceof AppActivity) {
                    ((AppActivity) getContext()).hideDialog();
                }
            }
        });
    }

    protected void updateView(){
        super.updateView();
        status = mDevice.getStateData().getStatus();
        if (status==null){
            return;
        }
        urltranslation();
        tv_musicName.setText(song_name);
        tv_singerName.setText(song_auth);
        if (status.getLength() == 0 && status.getProgress()==0){
            tv_Current_progress.setText("00:00");
            tv_aggregate_scheduling.setText("00:00");
        }else {
            simpleDateFormat.setTimeZone(TimeZone.getTimeZone("GMT+00:00"));
            String aggregate_time = simpleDateFormat.format(new Date(status.getLength() * 1000));
            tv_aggregate_scheduling.setText(aggregate_time);
            String current_time = simpleDateFormat.format(new Date(status.getProgress() * 1000));
            tv_Current_progress.setText(current_time);
            String progress_format = simpleDateFormat.format(new Date(status.getProgress() * 1000));
            tv_Current_progress.setText(progress_format);
            progress_length.setProgress(status.getProgress());
            current_progress = status.getProgress();
        }

        GlideApp.with(this)
                .load(song_pic_url)
                .placeholder(R.mipmap.icon_music_tacitlyapprove)
                .error(R.mipmap.icon_music_tacitlyapprove)
                .transform(new CenterCrop(),new RoundedCorners(20))
                .into(icon_music_tacitlyapprove);
        iv_stop_playing.setSelected(status.getPlaystate()==0);
        isSeekBarChanging = !iv_stop_playing.isSelected();
        playmode = status.getPlaymode();
        switch (status.getPlaymode()){
            case 2:
                icon_music_randomcycle.setImageResource(R.mipmap.icon_music_singlecycle);
                break;
            case 3:
                icon_music_randomcycle.setImageResource(R.mipmap.icon_music_listloop);
                break;
            case 5:
                icon_music_randomcycle.setImageResource(R.mipmap.icon_music_randomcycle);
                break;
            case 6:
                icon_music_randomcycle.setImageResource(R.mipmap.icon_music_loopplayback);
                break;
        }
        volume_length.setProgress(status.getVolume());
        progress_length.setMax(status.getLength());
        progress_length.setProgress(status.getProgress());
        seekBar_volume();
        seekBar_progress();
    }

    private void urltranslation() {
        try {
            //url编码转换
            song_name = URLDecoder.decode(status.getSongname(), "gbk");
            song_pic_url = URLDecoder.decode(status.getSongpicurl(), "gbk");
            song_auth = URLDecoder.decode(status.getSongauth(), "gbk");
        } catch (UnsupportedEncodingException | NullPointerException e) {
            e.printStackTrace();
        }
    }
}